const utils = require('../../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showDialog: false,
    showEditor: false,
    top: 20,
    name: '',
    sid: 0,//餐桌系统id
    tableId: '',//餐桌编号
    windowWidth: 330,
    heightStyle: 470,
    setType: 1,//1下单设置2餐桌设置
    payType: 1,//先付款后用餐2先用餐后付款
    tableList: []
  },
  // 下单设置
  setPayType: function (e) {
    let that = this;
    let type = e.currentTarget.dataset.type;
    let cardId = wx.getStorageSync('cardId');
    if (!cardId) {
      cardId = 0;
    }
    wx.request({
      url: app.globalData.host + '/api/staff/SetDiningOrder?staffid=' + cardId + '&content=' + type,
      success: function (res) {
      }
    })
    that.setData({
      payType: type
    })
  },

  // 餐桌设置/下单设置切换
  changeSetType: function (e) {
    let type = e.currentTarget.dataset.settype;
    if (type == 2) {
      this.getTableList();
    }
    this.setData({
      setType: type
    })
  },

  // 获取下单设置
  getStaffExtend: function () {
    let that = this;
    let cardId = wx.getStorageSync('cardId');
    if (!cardId) {
      cardId = 0;
    }
    wx.request({
      url: app.globalData.host + '/api/staff/GetStaffExtend?staffid=' + cardId + '&keyword=30',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Value) {
            that.setData({
              payType: res.data.Data.Value
            })
          }
        }
      }
    })
  },

  getTableList: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Restaurant/GetStoreDiningTables?storeid=' + app.globalData.storeId + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          for(var i = 0;i< res.data.Data.DiningTables.length; i++){
            var item = res.data.Data.DiningTables[i];
            item.SN = item.SN >0 ? 'SN: ' + item.SN : '扫码绑定';
          }
          that.setData({
            tableList: res.data.Data.DiningTables
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }

      }
    })
  },

  setTable: function () {
    let that = this;
    let name = that.data.name;
    let tableId = that.data.tableId;
    if (!name || !tableId) {
      wx.showToast({
        title: '请填写餐桌信息',
        duration: 1500,
        mask: true
      })
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/Restaurant/AddUpdateDiningTable',
      data: {
        Id: that.data.sid,
        StoreId: app.globalData.storeId,
        Uid: app.globalData.userInfo.Uid,
        Name: name,
        TableNumber: tableId
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.closeEditor();
          that.getTableList();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 编辑餐桌
  toEditor: function (e) {
    let that = this;
    let sid = e.currentTarget.dataset.sid;
    wx.request({
      url: app.globalData.host + '/api/Restaurant/GetDiningTable?id=' + sid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            sid: sid,
            tableId: res.data.Data.TableNumber,
            name: res.data.Data.Name
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
    that.setData({
      showEditor: !that.data.showEditor
    })
  },

  // 删除餐桌
  deleteTable: function (e) {
    let sid = e.currentTarget.dataset.sid
    let that = this;
    wx.showModal({
      title: '提示',
      content: '您确定要删除吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Restaurant/DeleteDiningTable?id=' + sid + '&uid=' + app.globalData.userInfo.Uid,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '删除成功',
                  mask: true,
                  duration: 1000
                })
                that.getTableList();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var windowWidth = wx.getSystemInfoSync().windowWidth * 0.88;
    var heightStyle = windowWidth * 1.42;
    this.setData({
      windowWidth: windowWidth,
      heightStyle: heightStyle
    })
    this.getStaffExtend();
    wx.hideShareMenu();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  bindName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindTableId: function (e) {
    this.setData({
      tableId: e.detail.value
    })
  },

  toAddTable: function () {
    this.setData({
      showEditor: !this.data.showEditor,
      sid: 0,
      name: '',
      tableId: ''
    })
  },
  closeEditor: function () {
    this.setData({
      showEditor: !this.data.showEditor
    })
  },
  showCode: function (e) {
    let sid = e.currentTarget.dataset.sid;
    let type = e.currentTarget.dataset.paytype;
    this.getSharePostBgm(sid,type);
    this.data.sid = sid;   
  },
  //扫一扫绑定
  toScan: function (e) {
    let that = this;
    let sid = e.currentTarget.dataset.sid;
    wx.scanCode({
      success(res) {     
        if (res.result) {
          let params = utils.getQuery(decodeURIComponent(res.result), 'scene');
          let param = params.match(/p-(\S*)/)[1];//参数
          let plist  = param.split('_');
          wx.showModal({
            title: '提示',
            content: '是否绑定此餐桌码: ' + plist[2],
            success(resModel) {
              if (resModel.confirm) {
                  that.bindSN(sid, plist[2]);
              }
            }
          })
        }else{
          wx.showToast({
            title: '绑定失败,无法识别二维码',
            icon: 'none'
          })
        }
      }
    })
  },
  //绑定SN序列号
  bindSN: function(sid,sn){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Restaurant/bindSN?id=' + sid + '&sn=' + sn,
      success: function (res) {
        if (res.data.Code == 0) {
          that.getTableList();
          wx.showToast({
            title: '绑定成功',
            icon:'none'
          })
        }else{
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }       
      }
    })
  },
  closeDialog: function () {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },

  getSharePostBgm: function(sid,type){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Restaurant/CreatePrintQrCode?id=' + sid+ '&payType=' + type,
      success: function(res){
        if(res.data.Code == 0){
          if(res.data.Data){
            that.setData({
              showDialog: !that.data.showDialog
            })
            wx.downloadFile({
              url: res.data.Data,
              success: function (suc) {
                let canvasimgbg = suc.tempFilePath;
                that.tablePosteCanvas(canvasimgbg);
              },
              fail: function () {
                wx.showToast({
                  title: '餐桌下载失败',
                  icon: 'none'
                })
              }
            })
          }else{
            wx.showToast({
              title: '生成失败',
            })
          }
        }else{
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },fail: function(err){

      }
    })
  },
  tablePosteCanvas: function(canvasimgbg){
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    const ctx = wx.createCanvasContext('myCanvas', that);
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;
      ctx.drawImage(canvasimgbg, 0, 0, width, height);
    }).exec()
    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },

  getBgimg: function () {
    var that = this;
    let url = 'https://static.711688.net.cn/upload/card/source/ua_2007241412548759603.jpg';
    wx.downloadFile({
      url: url,
      success: function (res) {
        let canvasimgbg = res.tempFilePath;
        that.getCode(canvasimgbg);
      },
      fail: function () {
        let canvasimgbg = '';
        that.getCode(canvasimgbg);
      }
    })
  },

  getCode: function (canvasimgbg) {
    var that = this
    var cardId = wx.getStorageSync("cardId")
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        // path: '/order/order/SessionCart/index?id=' + cardId + '&source=1&sid=' + that.data.sid,
        path: 'order/order/SessionCart/index?t=9&p=' + cardId + '#sid=' + that.data.sid + '#1',
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            wx.downloadFile({
              url: 'https://static.711688.net.cn/upload/user/' + res.data.Data,
              success: function (res) {
                let tableCode = res.tempFilePath;
                that.sharePosteCanvas(canvasimgbg, tableCode);
              },
              fail: function () {
                let tableCode = '';
                that.sharePosteCanvas(canvasimgbg, tableCode);
              }
            })
          }
        }
      },
    })
  },

  sharePosteCanvas: function (canvasimgbg, tableCode) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    const ctx = wx.createCanvasContext('myCanvas', that);
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;
      ctx.drawImage(canvasimgbg, 0, 0, width, height);
      let tableid = that.data.tableId;
      let name = that.data.name;
      if (tableid) {// 餐桌号
        ctx.setTextAlign('center');
        ctx.fillStyle = 'rgba(255, 255, 255, 1)';
        ctx.font = 'normal bold 24px sans-serif';
        ctx.fillText(tableid, width / 2, width * 174 / 375, width - 40);
      }
      if (tableCode) {
        ctx.drawImage(tableCode, (width - width * 193 / 375) / 2, width * 193 / 375, width * 193 / 375, width * 193 / 375);
      }
      if (name) {
        ctx.setTextAlign('center');
        ctx.fillStyle = 'rgba(255, 255, 255, 1)';
        ctx.font = 'normal bold 24px sans-serif';
        ctx.fillText(name, width / 2, width * 430 / 375, width - 40);
      }
    }).exec()
    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },
  //点击保存到相册
  saveShareImg: function () {
    let that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closeDialog();
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请删掉小程序再重新授权允许保存至相册',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  //监听用户滑动页面事件
  onPageScroll: function (e) {
    if(!this.data.showDialog){
      this.setData({
        top: e.scrollTop,
      })
    }
  }

  // 测试
   /**
   * 用户分享
   */
  // onShareAppMessage: function (res) {
  //   let that = this;
  //   var cardId = wx.getStorageSync("cardId");
  //   return {
  //     title: '餐桌分享',
  //     path: '/order/order/SessionCart/index?id=' + cardId + '&source=1&sid=' + that.data.sid,
  //     success: function (res) {
  //       wx.showModal({
  //         title: '提示',
  //         content: '转发成功',
  //         showCancel: false
  //       })
  //     }
  //   }
  // },
})